﻿using ECO.EventBus.Infrastructure;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace ECO.EventBus.Core
{
    public class EventBusBuilder
    {
        private readonly EventBusOptions _options = new();
        private readonly List<Assembly> _assembliesToScan = new();
        private readonly List<Type> _handlerTypes = new();

        public EventBusBuilder UsePool(bool usePool = true)
        {
            _options.UsePool = usePool;
            return this;
        }

        public EventBusBuilder WithMaxDegreeOfParallelism(int maxDegreeOfParallelism)
        {
            _options.MaxDegreeOfParallelism = maxDegreeOfParallelism;
            return this;
        }

        public EventBusBuilder ScanAssembly(Assembly assembly)
        {
            _assembliesToScan.Add(assembly);
            return this;
        }

        public EventBusBuilder ScanCurrentAssembly(List<Assembly>? assemblies =default)
        {
            if (assemblies != null && assemblies.Count > 0) _assembliesToScan.AddRange(assemblies);
            else _assembliesToScan.AddRange(AppDomain.CurrentDomain.GetAssemblies());
            return this;
        }

        public EventBusBuilder AddHandler<T>() where T : IEventHandler<IEvent>
        {
            _handlerTypes.Add(typeof(T));
            return this;
        }

        public EventBus Build()
        {
            var eventBus = new EventBus(_options);

            // 从程序集扫描处理器
            foreach (var assembly in _assembliesToScan)
            {
                eventBus.RegisterHandlersFromAssembly(assembly);
            }

            // 注册指定的处理器类型
            if (_handlerTypes.Count > 0)
            {
                eventBus.RegisterHandlersFromTypes(_handlerTypes.ToArray());
            }

            return eventBus;
        }
    }
}
